<?php

class Response_Http implements Response_Interface {
	protected $_header;
	protected $_body;
	protected $_charset;
	
	public function __construct() {
		$this->_header = array();
		$this->_body = array();
	}
	
	public function addHeader($name, $value) {
		$this->_header[$name] = $value;
	}
	
	public function addBody($body, $name = NULL) {
		$this->_body[$name] = $body;
	}
	
	public function clear() {
		$this->_header = array();
		$this->_body = array();
	}
	
	public function response() {
		if (!empty($this->_header) && !headers_sent()) {
			foreach ($this->_header as $name => $value) {
				header("{$name}: {$value};");
			}
		}
		if (!empty($this->_body)) {
			echo implode('', $this->_body);
		}
	}
	
	public function redirect($to, $time = 0) {
		$msg = __("系统将在{$time}秒之后自动跳转到{$url}");
		if (!headers_sent()) {
			header('Content-Type:text/html; charset='.JBlog::CHARSET);
			header("HTTP/1.1 301 Moved Permanently");
			if ($time == 0) {
				header("Location: {$url}");
			} else {
				header("refresh:{$time};url={$url}");
				echo($msg);
			}
		} else {
			echo '<meta http-equiv="Content-Type" content="text/html; charset='.JBlog::CHARSET.'"/>';
			echo '<script type="text/javascript">';
			echo 'window.location.href="'.$url.'";';
			echo '</script>';
			echo '<noscript>';
			echo '<meta http-equiv="refresh" content="'.$time.';url='.$url.'" />';
			echo '</noscript>';
			echo $msg;
		}
		die;
	}
}